package com.zhida.jiyangcenter.setting

import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.utils.*
import chooongg.http.APIException
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.APIAccount
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.utils.SP
import com.zhida.jiyangcenter.utils.request
import kotlinx.android.synthetic.main.activity_setting_pay_password.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@TitleBar(false)
@ContentLayout(R.layout.activity_setting_pay_password)
class SetPayPasswordActivity : BaseActivity() {
    override fun initConfig(savedInstanceState: Bundle?) {
        when {
            intent.getStringExtra("type") == "add" -> {
                title_bar.apply {
                    title("设置支付密码")
                    navigationIcon(R.drawable.iv_back_fill) {
                        finish()
                    }
                }
                rl_old_pay_password.gone()
                iv_old_pay_password.visible()
                ll_forget_yanzhengma.visible()
                tv_forget.gone()
            }
            intent.getStringExtra("type") == "editpws" -> {
                title_bar.apply {
                    title("修改支付密码")
                    navigationIcon(R.drawable.iv_back_fill) {
                        finish()
                    }
                }
                rl_old_pay_password.visible()
                iv_old_pay_password.visible()
                ll_forget_yanzhengma.gone()
                tv_forget.visible()
            }
            intent.getStringExtra("type") == "edit" -> {
                title_bar.apply {
                    title("修改支付密码")
                    navigationIcon(R.drawable.iv_back_fill) {
                        finish()
                    }
                }
                rl_old_pay_password.gone()
                iv_old_pay_password.visible()
                ll_forget_yanzhengma.visible()
                tv_forget.gone()
            }
        }
        tv_forget.setOnClickListener {
            startActivity<SetPayPasswordActivity> {
                putExtra("type", "edit")
            }
            onBackPressed()
        }
        tv_pay_password_queren.setOnClickListener {
            setPayPasswrod()
        }
        tv_bank_huoqu.setOnClickListener {
            getAuthCode()
        }
    }

    /**
     * 获取验证码
     */
    private fun getAuthCode() {
        btnAuthCodeDisable()
        tv_bank_huoqu.text = "获取中"
        lifecycleScope.request({
            APIAccount.service().sendCode(SP.account.get().toString())
        },
            object : BaseAPI<Any>() {

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }

                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    toast("验证码发送成功")
                    lifecycleScope.launch { authCodeCountDown() }

                }
            })

    }

    /**
     * 发送验证码后的倒计时
     */
    private suspend fun authCodeCountDown() {
        var time = 61
        while (time > 0 && !isFinishing) {
            time--
            if (time > 0) {
                withContext(Dispatchers.Main) {
                    tv_bank_huoqu.text = resString(R.string.login_been_send_auth_code, time)
                }
            } else {
                withContext(Dispatchers.Main) {
                    tv_bank_huoqu.setText(R.string.login_get_auth_code_retry)
                    btnAuthCodeEnable()
                }
            }
            delay(1000)
        }
    }

    private fun btnAuthCodeDisable() {
        tv_bank_huoqu.isEnabled = false
        tv_bank_huoqu.setTextColor(resColor(R.color.textGray))
    }

    private fun btnAuthCodeEnable() {
        tv_bank_huoqu.isEnabled = true
        tv_bank_huoqu.setTextColor(resColor(R.color.textVital))
    }

    private fun setPayPasswrod() {
        when {
            intent.getStringExtra("type") == "editpws" && et_old_pay_password.text.isNullOrEmpty() -> toast(
                "请输入原支付密码"
            )
            (intent.getStringExtra("type") == "edit"||intent.getStringExtra("type") == "add") && et_bank_yanzheng.text.isNullOrEmpty() -> toast(
                "请输入验证码"
            )
            et_pay_password.text.isNullOrEmpty() -> toast("请输入支付密码")
            et_confirm_pay_password.text.isNullOrEmpty() -> toast("请再次输入支付密码")
            et_pay_password.text.toString() != et_confirm_pay_password.text.toString() -> toast("两次输入的密码不同，请重新输入")
            et_pay_password.text.length < 6 -> toast("必须输入6位支付密码")
            et_confirm_pay_password.text.length < 6 -> toast("必须输入6位支付密码")
            else -> {
                when (intent.getStringExtra("type")) {
                    "add" -> {
                        lifecycleScope.request({
                            APIAccount.service().paysPassword(
                                et_confirm_pay_password.text.toString(),
                                et_pay_password.text.toString(),
                                et_bank_yanzheng.text.toString()
                            )
                        },object :BaseAPI<Any>(){
                            override fun onSuccess(t: Any?, state: Int, msg: String) {
                                finish()
                                tipSuccess("设置成功")
                            }

                            override fun onError(e: APIException) {
                                tipFail(e.eMessage)
                            }
                        })
                    }
                    "edit" -> {

                    }
                    "editpws" -> {
                        lifecycleScope.request({
                            APIAccount.service().paysPasswordChage(
                                et_old_pay_password.text.toString(),
                                et_pay_password.text.toString()
                            )
                        },object :BaseAPI<Any>(){
                            override fun onSuccess(t: Any?, state: Int, msg: String) {
                                finish()
                                tipSuccess("设置成功")
                            }

                            override fun onError(e: APIException) {
                                tipFail(e.eMessage)
                            }
                        })
                    }
                }

            }
        }
    }
}